<template>
  <div class="llm-container">
    <!-- 顶部标题区域 -->
    <div class="llm-header">
      <div class="header-title">
        <div class="logo-icon">
          <img src="/logo_02.png" alt="LLM 智能助手" class="logo-image" />
        </div>
        <h2 class="title-text">LLM 智能助手</h2>
      </div>
      <div class="header-subtitle">
        多语言翻译与分析助手
      </div>
    </div>

    <!-- 聊天容器 -->
    <div class="chat-container">
      <!-- 聊天历史区域 -->
      <div class="chat-history" ref="chatHistoryRef">
        <!-- AI欢迎语 -->
        <div v-if="chatMessages.length === 0" class="message ai-message welcome-message">
          <div class="ai-message-wrapper">
            <div class="ai-avatar">LLM</div>
            <div class="message-content">
              您好！我是您的AI助手，可以帮您进行多语言翻译、文本分析和内容生成。
            </div>
          </div>
        </div>

        <!-- 用户消息 -->
        <div
          v-for="(msg, index) in chatMessages"
          :key="index"
          :class="['message', msg.type === 'user' ? 'user-message' : 'ai-message']"
        >
          <div v-if="msg.type === 'user'" class="user-message-wrapper">
            <div class="message-content">
              {{ msg.content }}
            </div>
            <div class="user-avatar">
              <img
                v-if="userAvatar"
                :src="userAvatar"
                alt="用户头像"
                class="user-avatar-img"
                @error="handleAvatarError"
              />
              <i v-else class="fas fa-user"></i>
            </div>
          </div>
          <div v-else class="ai-message-wrapper">
            <div class="ai-avatar">LLM</div>
            <div class="message-content">
              <div v-if="msg.translation" class="translation-section">
                <p class="translation-label">翻译：</p>
                <p class="translation-text">{{ msg.translation }}</p>
              </div>
              <div v-if="msg.grammar" class="grammar-section">
                <p class="grammar-label">语法分析：</p>
                <div
                  v-for="(item, idx) in msg.grammar"
                  :key="idx"
                  class="grammar-item"
                >
                  {{ item }}
                </div>
              </div>
              <div v-if="msg.content && !msg.translation && !msg.grammar" class="plain-content">
                {{ msg.content }}
              </div>
            </div>
          </div>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="loading" class="message ai-message loading-message">
          <div class="ai-message-wrapper">
            <div class="ai-avatar">LLM</div>
            <div class="message-content">
              <span class="loading-dots">
                <span></span><span></span><span></span>
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="chat-input-area">
        <input 
          v-model="llmForm.inputText"
          type="text" 
          class="chat-input" 
          placeholder="询问关于多语言互译或东盟语言的问题..."
          @keyup.enter="handleSubmit"
          :disabled="loading"
        />
        <button 
          class="chat-send-btn" 
          @click="handleSubmit"
          :disabled="loading || !llmForm.inputText.trim()"
        >
          <i class="fas fa-paper-plane"></i>
        </button>
      </div>
    </div>

    <!-- 元数据信息（可选显示） -->
    <div v-if="metadata && result" class="metadata-container">
      <el-tag size="small" class="metadata-tag">模型: {{ metadata.model }}</el-tag>
      <el-tag size="small" type="info" class="metadata-tag">输入长度: {{ metadata.input_length }}</el-tag>
      <el-tag size="small" type="success" class="metadata-tag">输出长度: {{ metadata.output_length }}</el-tag>
    </div>
  </div>
  <div class="back-btn">
    <back-button></back-button>
  </div>
</template>

<script setup name="LlmProcess">
import { ref, reactive, onMounted, nextTick, computed } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { llmProcess, historySync, llmHistory } from '@/api'
import BackButton from '@/components/BackButton.vue'
import '@/assets/common.css'

const store = useStore()
const route = useRoute()
const router = useRouter()

const loading = ref(false)
const result = ref('')
const metadata = ref(null)
const chatHistoryRef = ref(null)
const chatMessages = ref([])

// 获取用户头像
const userAvatar = computed(() => {
  const userData = JSON.parse(localStorage.getItem('user') || '{}')
  return userData?.avatar_url || ''
})

// 处理头像加载失败
const handleAvatarError = (event) => {
  event.target.style.display = 'none'
  const parent = event.target.parentElement
  if (parent && !parent.querySelector('.fas.fa-user')) {
    const icon = document.createElement('i')
    icon.className = 'fas fa-user'
    parent.appendChild(icon)
  }
}

const llmForm = reactive({
  inputText: ''
})

/**
 * 滚动到底部
 */
const scrollToBottom = () => {
  nextTick(() => {
    if (chatHistoryRef.value) {
      chatHistoryRef.value.scrollTop = chatHistoryRef.value.scrollHeight
    }
  })
}

/**
 * 处理表单提交
 * 调用后端LLM接口，获取大模型的回答
 */
const handleSubmit = async () => {
  // 参数验证
  if (!llmForm.inputText.trim()) {
    ElMessage.warning('请输入问题')
    return
  }

  // 添加用户消息到聊天历史
  const userMessage = llmForm.inputText.trim()
  chatMessages.value.push({
    type: 'user',
    content: userMessage
  })
  
  // 清空输入框
  const currentInput = userMessage
  llmForm.inputText = ''
  
  // 滚动到底部
  scrollToBottom()

  loading.value = true
  result.value = ''
  metadata.value = null
  
  try {
    // 调用LLM API
    const response = await llmProcess({
      prompt: currentInput
    })
    
    // 检查响应状态
    if (response.data.status === 'success') {
      // 显示大模型的完整输出结果
      result.value = response.data.data.response
      // 保存元数据
      metadata.value = {
        model: response.data.data.model,
        input_length: response.data.data.input_length,
        output_length: response.data.data.output_length
      }
      
      // 解析AI回复（尝试识别翻译和语法分析）
      const aiResponse = result.value
      let aiMessage = {
        type: 'ai',
        content: aiResponse
      }
      
      // 尝试解析翻译和语法分析（如果响应包含特定格式）
      const translationMatch = aiResponse.match(/(?:翻译|Translation)[：:]\s*([^\n]+)/)
      const grammarMatch = aiResponse.match(/(?:语法分析|Grammar Analysis)[：:]/)
      
      if (translationMatch) {
        aiMessage.translation = translationMatch[1].trim()
      }
      
      if (grammarMatch) {
        // 提取语法分析部分
        const grammarText = aiResponse.substring(grammarMatch.index)
        const grammarItems = grammarText
          .split('\n')
          .filter(line => /^\d+\./.test(line.trim()) || line.trim().includes('('))
          .map(line => line.trim())
          .filter(line => line.length > 0)
        
        if (grammarItems.length > 0) {
          aiMessage.grammar = grammarItems
        }
      }
      
      // 添加AI消息到聊天历史
      chatMessages.value.push(aiMessage)
      
      // 滚动到底部
      scrollToBottom()
      
      ElMessage.success('处理成功')

      // 保存历史记录到本地store
      const snapshot = {
        form: { inputText: currentInput },
        result: result.value,
        metadata: metadata.value,
        chatMessages: chatMessages.value
      }
      const id = await store.dispatch('history/save', {
        type: 'llm',
        routeName: 'LLMProcess',
        snapshot
      })
      // 更新地址栏便于再次还原
      router.replace({ name: 'LLMProcess', query: { historyId: id } })
      
      // 保存到数据库（llm_history表）
      try {
        const token = localStorage.getItem('token')
        if (token) {
          await llmHistory.save({
            prompt: currentInput,
            response: result.value,
            model: metadata.value?.model || 'qwen-turbo',
            input_length: metadata.value?.input_length || currentInput.length,
            output_length: metadata.value?.output_length || result.value.length,
            session_state: snapshot
          })
        }
      } catch (e) {
        console.error('保存LLM历史记录到数据库失败:', e)
        // 不阻塞用户体验，静默失败
      }
      
      // 异步同步到后端（不阻塞体验）- 保留旧的同步方式作为备用
      try {
        historySync.save({
          history_uid: id,
          type: 'llm',
          route_name: 'LLMProcess',
          summary: `LLM: ${(currentInput || '').slice(0, 20)}${(currentInput || '').length > 20 ? '…' : ''}`,
          snapshot
        }).catch(() => { /* ignore history sync failure */ })
      } catch (e) { /* ignore history sync try-catch failure */ }
    } else {
      // 添加错误消息
      chatMessages.value.push({
        type: 'ai',
        content: response.data.message || '处理失败，请稍后重试'
      })
      scrollToBottom()
      ElMessage.error(response.data.message || '处理失败')
    }
  } catch (error) {
    console.error('LLM处理错误:', error)

    let errorMessage = 'LLM处理失败，请检查网络连接'

    // 针对不同类型的错误提供更具体的错误信息
    if (error.code === 'ECONNABORTED') {
      errorMessage = '请求超时，LLM响应时间过长，请稍后重试或简化问题'
    } else if (error.response?.status === 401) {
      errorMessage = '身份验证失败，请重新登录'
    } else if (error.response?.status === 500) {
      errorMessage = '服务器内部错误，请稍后重试'
    } else if (error.response?.data?.message) {
      errorMessage = error.response.data.message
    } else if (error.message) {
      errorMessage = error.message
    }

    // 添加错误消息
    chatMessages.value.push({
      type: 'ai',
      content: errorMessage
    })
    scrollToBottom()
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
  }
}

/**
 * 从历史记录还原
 */
const restoreFromHistory = () => {
  const historyId = route.query.historyId
  if (!historyId) return false
  const snapshot = store.getters['history/byId'](historyId)
  if (!snapshot) {
    ElMessage.info('未找到历史记录，已回退为默认页面')
    return false
  }
  llmForm.inputText = snapshot.form?.inputText || ''
  result.value = snapshot.result || ''
  metadata.value = snapshot.metadata || null
  // 还原聊天历史
  if (snapshot.chatMessages && Array.isArray(snapshot.chatMessages)) {
    chatMessages.value = snapshot.chatMessages
  } else if (snapshot.form?.inputText && snapshot.result) {
    // 兼容旧格式：从表单和结果重建聊天历史
    chatMessages.value = [
      { type: 'user', content: snapshot.form.inputText },
      { type: 'ai', content: snapshot.result }
    ]
  }
  loading.value = false
  scrollToBottom()
  return true
}

onMounted(() => {
  const restored = restoreFromHistory()
  if (restored) {
    const state = { historyId: route.query.historyId }
    window.history.replaceState(state, '', router.resolve({ name: 'LLMProcess', query: { historyId: route.query.historyId } }).href)
  }
})
</script>

<style scoped>
/* 使用 style.html 中定义的 CSS 变量 */
.llm-container {
  /* CSS 变量定义在组件根元素上 */
  --primary: #a78bfa;
  --primary-light: #ddd6fe;
  --primary-dark: #7c3aed;
  --text: #1e293b;
  --bg: #fdf4ff;
  --card-bg: #ffffff;
  --border: #e2e8f0;
  --shadow: rgba(149, 157, 165, 0.2);
  
  max-width: 1440px;
  margin: 0 auto;
  padding: 2rem;
  min-height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  background-color: var(--bg);
}

/* 顶部标题区域 */
.llm-header {
  margin-bottom: 2rem;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1rem;
}

.logo-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.logo-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
}

.title-text {
  font-size: 1.8rem;
  font-weight: 700;
  color: var(--text);
  margin: 0;
}

.header-subtitle {
  text-align: center;
  padding: 0.75rem 1.5rem;
  background-color: var(--primary-light);
  border-radius: 0.5rem;
  color: var(--primary-dark);
  font-weight: 500;
  font-size: 1.05rem;
}

/* 聊天容器 */
.chat-container {
  display: grid;
  grid-template-rows: 1fr auto;
  height: 600px;
  min-height: 600px;
  border: 1px solid var(--border);
  border-radius: 1rem;
  overflow: hidden;
  background-color: var(--card-bg);
  box-shadow: 0 4px 20px var(--shadow);
}

/* 聊天历史区域 */
.chat-history {
  display: flex;
  flex-direction: column;
  padding: 1.5rem;
  gap: 1.5rem;
  overflow-y: auto;
  background-color: var(--card-bg);
}

.chat-history::-webkit-scrollbar {
  width: 8px;
}

.chat-history::-webkit-scrollbar-track {
  background: var(--bg);
  border-radius: 4px;
}

.chat-history::-webkit-scrollbar-thumb {
  background: var(--primary-light);
  border-radius: 4px;
}

.chat-history::-webkit-scrollbar-thumb:hover {
  background: var(--primary);
}

/* 消息样式 */
.message {
  max-width: 80%;
  word-wrap: break-word;
  line-height: 1.6;
}

.user-message {
  align-self: flex-end;
}

.ai-message {
  align-self: flex-start;
}

/* 用户消息包装器 */
.user-message-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 0.75rem;
  justify-content: flex-end;
}

.user-message-wrapper .message-content {
  background-color: var(--primary);
  color: white;
  padding: 1rem 1.25rem;
  border-radius: 1rem;
  border-bottom-right-radius: 0.25rem;
  font-size: 0.95rem;
  max-width: 100%;
}

/* AI消息包装器 */
.ai-message-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 0.75rem;
  justify-content: flex-start;
}

.ai-message-wrapper .message-content {
  background-color: var(--primary-light);
  color: var(--text);
  padding: 1rem 1.25rem;
  border-radius: 1rem;
  border-bottom-left-radius: 0.25rem;
  font-size: 0.95rem;
  max-width: 100%;
}

/* AI头像样式 */
.ai-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: linear-gradient(135deg, var(--primary), var(--primary-dark));
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 0.75rem;
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgba(167, 139, 250, 0.3);
}

/* 用户头像样式 */
.user-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: var(--primary-light);
  color: var(--primary-dark);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1rem;
  flex-shrink: 0;
  border: 2px solid var(--primary);
  overflow: hidden;
  position: relative;
}

.user-avatar-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
  position: absolute;
  top: 0;
  left: 0;
}

.user-avatar i {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1;
}

/* 欢迎消息样式 */
.welcome-message {
  width: 100%;
  max-width: 100%;
  align-self: flex-start;
}

.welcome-message .ai-message-wrapper {
  align-items: center;
}

.welcome-message .message-content {
  background:var(--primary);
  color: white;
  padding: 1.25rem 1.5rem;
  border-radius: 1.25rem;
  border-bottom-left-radius: 0.5rem;
  font-size: 1rem;
  line-height: 1.7;
  box-shadow: 0 4px 15px rgba(167, 139, 250, 0.2);
}

.message-content {
  flex: 1;
}

/* 翻译部分 */
.translation-section {
  margin-bottom: 1rem;
}

.translation-label {
  font-weight: 600;
  margin-bottom: 0.5rem;
  color: var(--primary-dark);
  font-size: 0.9rem;
}

.translation-text {
  margin: 0;
  font-size: 1rem;
  line-height: 1.8;
}

/* 语法分析部分 */
.grammar-section {
  margin-top: 1rem;
}

.grammar-label {
  font-weight: 600;
  margin-bottom: 0.75rem;
  color: var(--primary-dark);
  font-size: 0.9rem;
}

.grammar-item {
  margin-bottom: 0.5rem;
  padding-left: 0.5rem;
  font-size: 0.95rem;
  line-height: 1.6;
}

.plain-content {
  white-space: pre-wrap;
  line-height: 1.8;
}

/* 加载状态 */
.loading-message {
  opacity: 0.7;
}

.loading-dots {
  display: inline-flex;
  gap: 0.5rem;
  align-items: center;
}

.loading-dots span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: var(--primary);
  animation: loading-bounce 1.4s infinite ease-in-out;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes loading-bounce {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 输入区域 */
.chat-input-area {
  display: flex;
  border-top: 1px solid var(--border);
  padding: 1rem;
  background: var(--card-bg);
  gap: 0.5rem;
  align-items: center;
}

.chat-input {
  flex-grow: 1;
  padding: 1rem 1.2rem;
  border-radius: 1.75rem;
  border: 1px solid var(--border);
  background: var(--bg);
  outline: none;
  color: var(--text);
  font-size: 0.95rem;
  transition: all 0.2s;
}

.chat-input:focus {
  border-color: var(--primary);
  box-shadow: 0 0 0 3px rgba(167, 139, 250, 0.1);
}

.chat-input:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.chat-send-btn {
  width: 3.5rem;
  height: 3.5rem;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background-color: var(--primary-dark);
  color: white;
  cursor: pointer;
  font-size: 1.3rem;
  transition: all 0.2s;
  flex-shrink: 0;
}

.chat-send-btn:hover:not(:disabled) {
  background-color: var(--primary);
  transform: scale(1.05);
}

.chat-send-btn:active:not(:disabled) {
  transform: scale(0.95);
}

.chat-send-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 元数据容器 */
.metadata-container {
  margin-top: 1.5rem;
  display: flex;
  gap: 0.75rem;
  flex-wrap: wrap;
  padding: 1rem;
  background-color: var(--card-bg);
  border-radius: 0.75rem;
  border: 1px solid var(--border);
}

.metadata-tag {
  font-size: 0.85rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .llm-container {
    padding: 1rem;
  }

  .chat-container {
    height: calc(100vh - 200px);
    min-height: 500px;
  }

  .message {
    max-width: 90%;
  }

  .user-message-wrapper {
    gap: 0.5rem;
  }

  .ai-message-wrapper {
    gap: 0.5rem;
  }

  .ai-avatar, .user-avatar {
    width: 32px;
    height: 32px;
  }

  .user-avatar {
    font-size: 0.9rem;
  }

  .ai-avatar {
    font-size: 0.65rem;
  }

  .title-text {
    font-size: 1.5rem;
  }

  .logo-icon {
    width: 36px;
    height: 36px;
  }

  .header-subtitle {
    font-size: 0.95rem;
    padding: 0.6rem 1rem;
  }
}

@media (max-width: 480px) {
  .chat-container {
    height: calc(100vh - 180px);
    min-height: 400px;
  }

  .ai-avatar, .user-avatar {
    width: 28px;
    height: 28px;
  }

  .user-avatar {
    font-size: 0.8rem;
  }

  .ai-avatar {
    font-size: 0.55rem;
  }

  .logo-icon {
    width: 32px;
    height: 32px;
  }

  .title-text {
    font-size: 1.3rem;
  }

  .chat-input-area {
    padding: 0.75rem;
  }

  .chat-send-btn {
    width: 3rem;
    height: 3rem;
    font-size: 1.1rem;
  }
}
</style>

